package code.example.zookeeper.apply.config;

import code.example.zookeeper.ZookeeperHolder;
import org.apache.zookeeper.data.Stat;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class ConfigNode {
    String name;
    String value;
    List<ConfigNode> configNodeList= new LinkedList<ConfigNode>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public List<ConfigNode> getConfigNodeList() {
        return configNodeList;
    }

    public void setConfigNodeList(List<ConfigNode> configNodeList) {
        this.configNodeList = configNodeList;
    }
    private ConfigNode findOrCreateConfigNode(String next ){
        Optional<ConfigNode> optional = configNodeList.stream().filter(new Predicate<ConfigNode>() {
            @Override
            public boolean test(ConfigNode configNode) {
                return next.startsWith(configNode.getName());
            }
        }).findAny();
        if(optional.isPresent()){
            return optional.get();
        }else{
            ConfigNode configNode =   new ConfigNode();
            configNodeList.add(configNode);
            return configNode;
        }
    }
    public void inject(String key,String value){
        int index = key.indexOf(".") ;
        if(index != -1 ){
            String prefix = key.substring(0,index);
            String next = key.substring(index+1);
            this.setName(prefix);
            ConfigNode configNode = findOrCreateConfigNode(next);
            configNode.inject(next,value);
        }else{
            this.setName(key);
            this.setValue(value);
        }
    }

    public void createZookeeperConfigNode(ZookeeperHolder zookeeperHolder ,String path) throws Exception {
        String zkPath = path+"/"+this.name;
        Stat stat = zookeeperHolder.exists(zkPath);
        if(stat ==null){
            zookeeperHolder.create(zkPath);
        }
        if(!StringUtils.isEmpty(this.value)){
            zookeeperHolder.setData(zkPath,this.value);
        }
        Iterator<ConfigNode> iterator = this.configNodeList.iterator();
        while(iterator.hasNext()){
            ConfigNode configNode = iterator.next();
            configNode.createZookeeperConfigNode(zookeeperHolder,zkPath);
        }
    }
}
